import {showConfirmDialog, showSuccessToast, showToast} from "vant";
import router from "@/router";
import Clipboard from "vue-clipboard3";

// 显示[操作成功]提示
export function showOptSuccessToast() {
    showSuccessToast("操作成功")
}

/**
 * 显示消息提示框
 * @param content 提示的标题
 */
export function toast(content) {
    showToast({
        icon: 'none',
        title: content,
    });
}

/**
 * 显示模态弹窗
 * @param content 提示的标题
 */
export function showConfirm(content) {
    return new Promise((resolve) => {
        showConfirmDialog({
            title: '提示',
            content: content,
            success: function (res) {
                resolve(res);
            },
        });
    });
}

/**
 * 参数处理
 * @param params 参数
 */
export function tansParams(params) {
    let result = '';
    for (const propName of Object.keys(params)) {
        const value = params[propName];
        var part = encodeURIComponent(propName) + '=';
        if (value !== null && value !== '' && typeof value !== 'undefined') {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (
                        value[key] !== null &&
                        value[key] !== '' &&
                        typeof value[key] !== 'undefined'
                    ) {
                        let params = propName + '[' + key + ']';
                        var subPart = encodeURIComponent(params) + '=';
                        result +=
                            subPart + encodeURIComponent(value[key]) + '&';
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + '&';
            }
        }
    }
    return result;
}

// 跳转到错误页面 type:push、replace
export function showErrorPage(type, errorMsg) {
    const param = {path: '/error', query: {errorMsg: errorMsg}}

    if ('push' === type) {
        router.push(param)
    } else if ('replace' === type) {
        router.replace(param)
    }
}

// 判断是否是需要通知前端的异常
export function isNotifyException(res) {
    return res.data.code === 10000
}

// 复制文本到剪贴板
export function copyText(text) {
    Clipboard().toClipboard(text);
    showSuccessToast("复制成功")
}

// 获取url上的参数
export function getUrlParam(name) {
    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    return urlParams.get(name)
}